import React, { useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
import CpasTableFs, { ImportToTitle, ExportToTitle } from "~/public/cpas-business/cpas-table/CpasTableFs";
import ChangeTemplatePopup from "~/public/cpas-business/components-bs/components/TemplatePopup/ChangeTemplatePopup";
import SaveTemplatePopup from "~/public/cpas-business/components-bs/components/TemplatePopup/SaveTemplatePopup";
import Details from "~/public/cpas-business/cpas-table/ExcelGrid/components/Validator/CheckDetails"
import { CpasIcon } from '~/public/cpas-ui';
import '@/pages/components/StyleFile/btnStyle.less';
import { Button } from "devextreme-react";
import { useModel } from "umi";
import {
    getColumnsMapByReport, getPeriodInfo, getRowsMapByReport, getTableperiodAndPointList,
    getWscwbbData, gettableIsVerifyTid, templateInitApi, queryVerifyStatefs, saveTemplateApi, reCalculateNotesInitApi, getTableperiodAndPointList111
} from './service';
import "./index.less";
import notify from "devextreme/ui/notify";
import { UpdateCpasTableHeader, arrayJoinStr, UpdateCpasTableDataZero, UpdateCPASTableData, changeTitleTime, Md5_16, extractFileInfo } from '@/utils';
// import { UpdateCpasTableDataZero, UpdateCPASTableData } from '~/public/cpas-ui/components-ui/components/ExcelGrid/Tools/index';
import CpasTableChangePupop from "../../components/CpasTableChangePupop";
// import { Upload } from "antd";, { Item as ButtonItem }
import DropDownButton from 'devextreme-react/drop-down-button';
import axios from "axios";

import PopupComponents from '../PopupComponents';
import PageLoading from "../PageLoading";
import moment from "moment";


const CommonCpasTable = React.forwardRef((props: any, ref: any) => {
    const { CPASTableProps, tableNameGroup, excelParams, antTabsTabPaneDetail, cpasChangeSpinAntTabs, commonCpasTableDisplay, isInitBtn, changeIsInitBtn, postCpasTableData } = props;
    const { CPASTableType, WscwbbType, tableName, titleName, origin, tableRiCurrency, tabsIndex } = CPASTableProps;
    const { initialState } = useModel('@@initialState');
    const { cpasTableZeroReplace, negationRow } = initialState?.settings;
    const { dbname, zcbfName } = initialState?.curPart as API.CurPart;
    const [rowsMapList, setRowsMapList] = useState<any[]>([]);
    const [columnsMapList, setColumnsMapList] = useState<any[]>([]);
    const cpasTableFsRef = useRef<any>(null);
    const saveTemplatePopupRef = useRef<any>();
    const changeTemplatePopupRef = useRef<any>();
    const [showMenuToolBar, setShowMenuToolBar] = useState<boolean>(false);
    const [spinLoad, setSpinLoad] = useState<boolean>(false);
    const [serverDataLen, setServerDataLen] = useState<number>(2);
    const cpasTableChangePupopRef = useRef<any>(null);
    const [openDetails, setOpenDetails] = useState<boolean>(false);
    const cpasTableTid = useRef<any>(''); // tid

    const [titleYearStr, setTitleYearStr] = useState<string>(' ');

    const [commonCpasTableNot, setCommonCpasTableNot] = useState<string>(' ');

    const [titleYearExport, setTitleYearExport] = useState<string>(' ');
    const [titleYearExportMin, setTitleYearExportMin] = useState<string>(' ');
    const PopupComponentsRef = useRef<any>(null);
    const [loadingContent, setLoadingContent] = useState<string>('加载中...');
    // const [verifyResult, setVerifyResult] = useState<any[]>([]);

    const [resultListData, setResultListData] = useState<any>({
        verifyResult: [],
        isBackAll: false,
    });

    //注意mapList接收的映射源为数组结构(handson所决定) [,,,]
    function dataObjToArray(objData: any[]) {
        const result = [""];
        objData.forEach((item) => {
            result.push(item.value);
        });
        return result;
    }

    //初始化表格映射数据源
    async function loadRowsMapData() {
        const rowsMapListData = await getRowsMapByReport({ dbname });
        setRowsMapList(dataObjToArray(rowsMapListData.data));
    }
    async function loadColumnsMapData() {
        const columnsMapListData = await getColumnsMapByReport({ dbname });
        setColumnsMapList(dataObjToArray(columnsMapListData.data));
    }
    // 获取真是的CPASTable的ref
    const getRealCPASTableRef = () => {
        if (cpasTableFsRef.current) {
            const realHandSonGridRef = cpasTableFsRef.current.handsonTableFs.current;
            return realHandSonGridRef;
        }
        return null;
    }
    const fetchTablePeriodList = useCallback(async () => {
        setSpinLoad(true);
        setLoadingContent('获取年度中...');
        const isPoint = tabsIndex < 3 ? 0 : 1;
        let cpasTableTitleList: string[] = [];
        let cpasTableCmapList: any[] = [];
        const resYear = await getPeriodInfo({ dbname });
        if (resYear.success) {
            const resSetting = await getTableperiodAndPointList({ dbname, isDesc: true, reportType: isPoint });
            if (resSetting.success) {
                if (resYear.data.yearCnt > 1) {
                    setTitleYearStr(' ');
                    setTitleYearExport(' ');
                    setTitleYearExportMin(' ');
                    setCommonCpasTableNot('commonCpasTableNotTitle');
                    window.localStorage.setItem(`${excelParams.excelFileName}_${dbname}`, JSON.stringify({}));
                } else {
                    let yearStrTitle = " ";
                    let ndYear = " ";
                    let yearStr = " ";
                    if (resSetting.data[0]?.reportDate) {
                        if (tabsIndex < 3) {
                            const returnTime = changeTitleTime(resSetting.data[0].reportDate, resSetting.data[1].reportDate);
                            yearStr = returnTime.titleTimeA;
                            yearStrTitle = returnTime.titleTimeA;
                            ndYear = returnTime.titleTimeB;
                            let titleDateObj = { ndYear, yearStr };
                            // // 本地存储 持久化数据
                            window.localStorage.setItem(`${excelParams.excelFileName}_${dbname}`, JSON.stringify(titleDateObj));
                        } else {
                            const getTitleDateObj: any = window.localStorage.getItem(`${excelParams.excelFileName}_${dbname}`);
                            yearStrTitle = resSetting.data[0].reportDate;
                            ndYear = resSetting.data[0].reportDate;
                            yearStr = JSON.parse(getTitleDateObj)?.yearStr ?? " ";

                        }
                    } else {
                        notify(`3获取批量设置的日期报错！`, "error", 2000);
                    }
                    setTitleYearExportMin(yearStr);
                    setTitleYearExport(ndYear);
                    setTitleYearStr(yearStrTitle);
                    setCommonCpasTableNot(' ');
                }
                if (resSetting.data?.length) {
                    cpasTableTitleList = resSetting.data.map((item: { title: string }) => {
                        const momentDate = moment(item.title, "YYYY.MM.DD", true);
                        if (momentDate.isValid()) {
                            item.title = momentDate.format("YYYY年M月D日");
                        }
                        return item.title;
                    });
                    cpasTableCmapList = resSetting.data.map((item: { data_id: any, fieldName: string }) => {
                        return {
                            year_id: item.data_id,
                            year_fieldName: item.fieldName
                        };
                    });
                }

                console.log(cpasTableTitleList, cpasTableCmapList, '@@@');
                return { data: cpasTableCmapList, dataTitle: cpasTableTitleList, success: true };
            } else {
                notify(`获取批量设置的数据列表失败！`, "error", 2000);
                return { data: [], dataTitle: [], success: true };
            }

        } else {
            notify(`获取首页年度列表失败！`, "error", 2000);
            setSpinLoad(false);
            setLoadingContent(' ');
        }
        return { data: [], dataTitle: [], success: true };

    }, []);



    // 业务要加那个预制校验
    const changeCrticulationVerify = async (dataRef: any) => {
        const verifyResult = dataRef.articulationVerifyService.artParseResultList;
        const formulaList = dataRef.articulationVerifyService.artVerifyFormulaList;
        const parseList = await dataRef.articulationVerifyService.parseArtVerifyFormula(formulaList);
        // 增加 单点标志值 默认 []
        const resultItem = dataRef.articulationVerifyService.artResultItem;
        if (resultItem?.length > 0) {
            dataRef.articulationVerifyService.markBeVerifiedItem(
                resultItem[0],
                true,
                true
            );
        } else if (verifyResult.length > 0) {
            dataRef.articulationVerifyService.batchMarkBeVerifiedItem(parseList);
        }
    }


    const loadTableByServerData = async (serverName: string) => {
        setSpinLoad(true);
        setLoadingContent('加载中...');
        let serverData: any;
        const realrealHandSonGridRefRef = getRealCPASTableRef();
        if (realrealHandSonGridRefRef) {
            console.log('@@@ 获取真是的CPASTable的ref', realrealHandSonGridRefRef);
            try {
                serverData = await realrealHandSonGridRefRef.loadTableByServer(serverName);
                console.log('--------serverData初始数据 @@@', serverData);
                if (serverData.data) {
                    const res = await gettableIsVerifyTid({
                        tableName,
                        dbname,
                        isTid: true
                    });
                    if (res.success && res.data?.length) {
                        const tid = res.data[0].tid;
                        cpasTableTid.current = res.data[0].tid;
                        console.log(`@@@  ${serverName}`, cpasTableTid.current);
                        const verifyData = await realrealHandSonGridRefRef.loadVerifyByServer(tid);
                        let fsParams = {
                            dbname,
                            tid: tid,
                            type: "fs"
                        }
                        const lodaTableZl = await queryVerifyStatefs(fsParams);
                        if (lodaTableZl.code === 200) {
                            realrealHandSonGridRefRef.setVerifyData(verifyData);
                            console.log(verifyData.artParseResultList, '@@@ verifyData.artParseResultList');
                            // setVerifyResult(verifyData.artParseResultList);
                            setResultListData({
                                verifyResult: verifyData.artParseResultList,
                                isBackAll: false,
                            });
                        }
                    } else {
                        notify(`获取tid失败！`, "error", 2000);
                    }
                    await realrealHandSonGridRefRef.reloadTable(serverData, 'fs', null, true)
                    changeCrticulationVerify(realrealHandSonGridRefRef);
                    setServerDataLen(serverData.data.length);
                    setSpinLoad(false);
                    setLoadingContent(' ');
                    console.log('   数据@@@ tid', origin);
                    notify(`获取该表数据成功！`, "success", 2000);
                    return {
                        data: serverData,
                        msg: serverData.msg,
                        success: true
                    };
                } else {
                    setServerDataLen(2);
                    notify(`获取数据失败：${serverData.msg}！`, "warning", 2000);
                    setSpinLoad(false);
                    setLoadingContent(' ');
                    realrealHandSonGridRefRef.resetTable(CPASTableType);
                    return {
                        data: [],
                        msg: serverData.msg,
                        success: false
                    };
                }


            } catch (e) {
                setServerDataLen(2);
                notify(`没有该表:【${serverName}】的数据！`, "warning", 2000);
                setSpinLoad(false);
                setLoadingContent(' ');
                realrealHandSonGridRefRef.resetTable(CPASTableType);
                return {
                    data: [],
                    msg: `没有该表:【${serverName}】的数据！`,
                    success: false
                };
            }
        }
        return;
    }


    const reloadServerData = async (serverName: string) => {
        loadRowsMapData();
        loadColumnsMapData();
        let serverCpasTableData: any;
        let tempColsNumber: number;
        let returnData: any = {};
        const realHandSonGridRef = getRealCPASTableRef();
        if (realHandSonGridRef) {
            try {
                tempColsNumber = (origin === '审定财务' && tableName !== '审定财务-现金流补充资料表') ? 3 : 2;
                serverCpasTableData = await realHandSonGridRef.loadTableByServer(serverName);
                returnData = { serverCpasTableData, tempColsNumber };
            } catch (e) {
                notify(`没有该表:【${serverName}】的数据！`, "warning", 2000);
                setServerDataLen(2);
                realHandSonGridRef.resetTable(CPASTableType);
                returnData = { serverCpasTableData: {}, tempColsNumber: null }
            }
        }
        return returnData;
    }

    /** updateCmaps  年度和QCYE拼接，生成数组 [xm, '2016QCYE', '2016QMYE', '2015QCYE', '2015QMYE']
     * yearDatas 多年度的数组 [2016,2017,2018]
     *
     * 返回OBJ { yearJoin, yearJoinXM };
     *
    */
    const updateCmaps = (yearDatas: any[]) => {
        let yearJoin: any = [];
        if (!yearDatas?.length) return { yearJoin, filterStr: '' };

        let tempQC: string; let tempQM: string; let tempSQ: string;
        let filterStr: string;
        if (origin === '审定财务') {
            if (WscwbbType === '利润类' || WscwbbType === '现金流量类' || WscwbbType === '现金流补充资料类') {
                tempQC = 'QCSDLJFSE';
                tempQM = 'SDLJFSE';
                tempSQ = ''
            } else {
                tempQC = 'QCSDS';
                tempQM = 'SDS';
                tempSQ = 'SNSDS'
            }
        } else {
            if (WscwbbType === '利润类' || WscwbbType === '现金流量类' || WscwbbType === '现金流补充资料类') {
                tempQC = 'QCWSLJFSE';
                tempQM = 'WSLJFSE';
                tempSQ = ''
            } else {
                tempQC = 'QCWSS';
                tempQM = 'WSS';
                tempSQ = 'SNS'
            }
        }

        const SQQMData = yearDatas.filter(item => {
            return item.year_fieldName === 'SQQM';
        })

        // const lastIndex = yearDatas.length - 1;
        // const minNum = Math.min(...yearDatas);
        const isTrue = tabsIndex < 3;
        yearDatas.forEach((item: any) => {
            if (isTrue) {
                if (item.year_fieldName === 'QM') {
                    return yearJoin.push(`${item.year_id}${tempQM}`)
                }
                if (item.year_fieldName === 'QC') {
                    return yearJoin.push(`${item.year_id}${tempQC}`)
                }
                if (item.year_fieldName === 'SQQM') {
                    return yearJoin.push(`${item.year_id}${tempSQ}`)
                }
            } else {
                if (item.year_fieldName === 'BQ') {
                    return yearJoin.push(`${item.year_id}${tempQM}`)
                }
                if (item.year_fieldName === 'SQ') {
                    return yearJoin.push(`${item.year_id}${tempQC}`)
                }
            }
        });

        if (isTrue && SQQMData.length) {
            filterStr = `${tempQC},${tempQM},${tempSQ}`;
        } else {
            filterStr = `${tempQC},${tempQM}`;
        }
        return { yearJoin, filterStr };
    }

    // 刷新
    const cpasTableReload = async () => {
        const resData = await fetchTablePeriodList();
        let realYearData: any[] = resData.data;
        let realYearDataTitle: any[] = resData.dataTitle;
        let getCpasTableData: any;
        if (tableName) {
            getCpasTableData = await reloadServerData(tableName);
        }
        const { serverCpasTableData, tempColsNumber } = getCpasTableData;
        console.log('------cpasTableReload从数据库内捞出来的： 数据@@@ ------',
            `当前长度：${serverDataLen}`, serverCpasTableData, tempColsNumber);
        if (!serverCpasTableData || !tempColsNumber) return notify(`没有该表:【${tableName}】的数据！`, "error", 2000);
        if (tabsIndex > 5) {
            setSpinLoad(false);
            setLoadingContent(' ');
            return;
        };
        try {
            const realHandSonGridRef = getRealCPASTableRef();
            if (realHandSonGridRef) {
                setSpinLoad(true);
                setLoadingContent('正在刷新获取数据...');
                // cpasTableTid.current = serverData.data.cpasTable.tid;
                const result = realHandSonGridRef.getCurrentTableMaps();
                const newCmaps = updateCmaps(realYearData);
                const titleChange = tabsIndex < 3;
                // UpdateCpasTableHeader  生成新的CpasTableHeader 修改HeaderData的函数
                serverCpasTableData.header = UpdateCpasTableHeader(serverCpasTableData.header, realYearDataTitle, tempColsNumber, titleChange);
                console.log('------生成新的CpasTableHeader 数据@@@------', serverCpasTableData.header);
                // updateCpasTableData 生成新的CpasTableData 补零的函数
                serverCpasTableData.data = UpdateCpasTableDataZero(serverCpasTableData.data, newCmaps.yearJoin, tempColsNumber);
                console.log('------生成新的CpasTableData 补零的函数 -    数据@@@------', serverCpasTableData);

                if (realYearData.length === 0) {
                    setSpinLoad(false);
                    setLoadingContent(' ');
                    realHandSonGridRef.reloadTable(serverCpasTableData, 'fs', null, true)
                    return;
                }

                const keysStr = arrayJoinStr(result?.rmaps);
                const colsStr = arrayJoinStr(newCmaps.yearJoin);
                const res = await getWscwbbData({
                    dbname,
                    type: WscwbbType,
                    cols: colsStr,
                    keys: keysStr,
                    filterConditions: newCmaps.filterStr
                });
                if (res.success) {
                    const cpasData = UpdateCPASTableData(res.data, serverCpasTableData.data, tempColsNumber, negationRow);
                    serverCpasTableData.data = cpasData;
                    console.log('------插入data之后的数据 cpasData  -  数据@@@------', res.data, cpasData, serverCpasTableData);
                    await realHandSonGridRef.reloadTable(serverCpasTableData, 'fs', null, true)
                    changeCrticulationVerify(realHandSonGridRef);
                    setServerDataLen(serverCpasTableData.data.length);
                    notify(`刷新成功！`, "success", 2000);
                } else {
                    notify(`请核对对应关系！`, "warning", 2000);
                }
                setSpinLoad(false);
                setLoadingContent(' ');
            }
        } catch (error) {
            setSpinLoad(false);
            setLoadingContent(' ');
            notify('刷新失败！', "warning", 2000);
        }
    };


    /**
     * cpas表格数据存储到线上
    */
    const saveToServer = async () => {
        const realHandSonGridRef = getRealCPASTableRef();
        if (realHandSonGridRef) {
            try {
                const Md5_16Str = Md5_16(tableName);
                const res = await realHandSonGridRef.saveToServer(tableName, CPASTableType, Md5_16Str);
                if (res) {
                    const serverData = await realHandSonGridRef.loadTableByServer(tableName);
                    await realHandSonGridRef.reloadTable(serverData, 'fs', null, true)
                    const dataGrid = realHandSonGridRef.getCpasTableGrid();
                    setServerDataLen(dataGrid.data.length);
                    notify(`保存成功！`, "success", 2000);
                    antTabsTabPaneDetail();
                    changeCrticulationVerify(realHandSonGridRef);
                    return true;
                }
                return false;
            } catch (error) {
                notify(`保存失败！`, "error", 2000);
                return false;
            }
        }
        return false;
    }

    // 保存并刷新
    const saveAndReload = async () => {
        const resSave = await saveToServer();
        if (resSave) {
            cpasTableReload();
        }
    };

    //  导出带标题头的xlsx
    const exportChange = () => {
        ExportToTitle(cpasTableFsRef.current, "primary");
    };
    //  导入带标题头的xlsx
    const importChange = (file: any, self: any) => {
        ImportToTitle(file, self);
    };

    const exportExcel = async () => {
        // console.log('@@@', excelParamsData);
        const dialog_result = await window.electronComponents.showSaveDialog("xlsx", `${excelParams.excelFileName}.xlsx`);
        if (!dialog_result.canceled) {
            let tempExcelParams = { ...excelParams };
            let changeTableDate: any = [];
            tempExcelParams.excelInfo.forEach((item: any, index: number) => {
                if (titleYearStr) {
                    if (index < 2) {
                        item.tableDate = titleYearExportMin;
                    } else {
                        item.tableDate = titleYearExport;
                    }
                } else {
                    item.tableDate = ' ';
                }
                changeTableDate.push(item);
            });
            const excelParamsData = { ...tempExcelParams, excelInfo: changeTableDate };
            const fileData = extractFileInfo(dialog_result.filePath);
            const params = {
                ...excelParamsData,
                directoryPath: fileData.dirName,
                excelFileName: fileData.fileName
            };
            const url = `/cpasApi/cpasTableEngine/getCpatableToBatchExportExcel`;
            const data = await axios.post(url, params);
            const tempMsg = 'EBUSY: resource busy or locked, open';
            const isTrue = data.data.msg.includes(tempMsg);
            if (isTrue) {
                return {
                    code: data.data.code,
                    msg: "文件已被程序打开，需要关闭已被打开的文件。",
                    ok: data.data.data,
                    type: '导出'
                };
            }
            return {
                code: data.data.code,
                msg: data.data.msg,
                ok: data.data.data,
                type: '导出'
            };
        }
        return {
            code: 404,
            msg: '取消了选择路径！',
            ok: false,
            type: '取消'
        };
    }
    // 打开勾稽校验详情
    const openDetail = async () => {
        const realHandSonGridRef = getRealCPASTableRef();
        if (realHandSonGridRef) {
            const verifyData = await realHandSonGridRef.articulationVerifyService.artParseResultList;
            setResultListData({
                verifyResult: verifyData,
                isBackAll: false,
            });
        } else {
            notify(`获取verifyData失败！`, "error", 2000);
        }
        setOpenDetails(true);
        //realHandSonGridRef.articulationVerifyService.clearArtVerifyMark()
    }

    // 关闭勾稽校验详情
    const closeDetail = () => {
        setOpenDetails(!openDetails);
    }


    const batchExport = async () => {
        const res = await exportExcel();
        if (res.type === '导出') {
            if (res.ok) {
                notify(`导出成功！`, "success", 2000);
            } else {
                if (res.code == 500) {
                    PopupComponentsRef.current.show({
                        title: "提示信息",
                        content: res.msg,
                        cancelText: "取消",
                        okText: "确定",
                        okCallback: () => {
                            PopupComponentsRef.current.closeDia();
                        },
                    });
                }

            }
        }
    }



    const useEffectFun = async () => {
        await fetchTablePeriodList();
        if (tableName) {
            const res = await loadTableByServerData(tableName);
            if (res?.success) {
                await loadRowsMapData();
                await loadColumnsMapData();
                changeIsInitBtn();
                // await cpasTableReload();
            }
        }
    };

    useEffect(() => {
        if (!isInitBtn) {
            useEffectFun();
        }
    }, []);

    useImperativeHandle(ref, () => ({
        CPASInit: () => {
            useEffectFun();
        },
        clearDesignTableName: async (tempTableName: any) => {
            const realHandSonGridRef = getRealCPASTableRef();
            if (realHandSonGridRef) {
                return await realHandSonGridRef.removeTableByServer(tempTableName, '', 'fs');
            }
        },
        CPASOpenDetail: () => {
            openDetail();
        }
    }));

    const fetchTablePeriodList1111 = useCallback(async () => {
        setSpinLoad(true);
        setLoadingContent('获取年度中...');
        // const isPoint = tabsIndex < 3 ? 0 : 1;
        let cpasTableTitleList: string[] = [];
        let cpasTableCmapList: any[] = [];
        let cpasTableTitleList1: string[] = [];
        let cpasTableCmapList1: any[] = [];
        const resYear = await getPeriodInfo({ dbname });
        if (resYear.success) {
            const resSetting = await getTableperiodAndPointList111({ dbname, isDesc: true });
            if (resSetting.success) {
                if (resSetting.data?.length) {
                    resSetting.data.forEach((item: { data_id: any, fieldName: string; reportType: number; title: string }) => {
                        if (item.reportType === 1) {
                            cpasTableTitleList1.push(item.title);
                            cpasTableCmapList1.push({
                                year_id: item.data_id,
                                year_fieldName: item.fieldName
                            });
                        } else {
                            const momentDate = moment(item.title, "YYYY.MM.DD", true);
                            if (momentDate.isValid()) {
                                item.title = momentDate.format("YYYY年M月D日");
                            }
                            cpasTableTitleList.push(item.title);
                            cpasTableCmapList.push({
                                year_id: item.data_id,
                                year_fieldName: item.fieldName
                            });
                        }
                    });
                }
                setSpinLoad(false);
                return { data: cpasTableCmapList, dataTitle: cpasTableTitleList, data1: cpasTableCmapList1, dataTitle1: cpasTableTitleList1, success: true };
            } else {
                setSpinLoad(false);
                notify(`获取批量设置的数据列表失败！`, "error", 2000);
                return { data: [], dataTitle: [], data1: [], dataTitle1: [], success: true };
            }
        } else {
            notify(`获取首页年度列表失败！`, "error", 2000);
            setSpinLoad(false);
            setLoadingContent(' ');
        }
        return { data: [], dataTitle: [], data1: [], dataTitle1: [], success: true };

    }, []);

    const updateCmaps111111 = (yearDatas: any, postCpasData: any) => {

        console.log(yearDatas, postCpasData, '@@@');
        let tempQC: string; let tempQM: string; let tempSQ: string;
        let filterStr: string;
        let yearJoin: any = [];


        const SQQMData = yearDatas.data.filter((item: any) => {
            return item.year_fieldName === 'SQQM';
        });
        const SQQMData1 = yearDatas.data1.filter((item: any) => {
            return item.year_fieldName === 'SQQM';
        });

        let tempDataArr: any = [];
        postCpasData.forEach((item: any, tempInex: number) => {
            if (origin === '审定财务') {
                // if (item.WscwbbType === '利润类' || item.WscwbbType === '现金流量类' || item.WscwbbType === '现金流补充资料类') {
                //     tempQC = 'QCSDLJFSE';
                //     tempQM = 'SDLJFSE';
                //     tempSQ = '';
                // } else {
                //     tempQC = 'QCSDS';
                //     tempQM = 'SDS';
                //     tempSQ = 'SNSDS';
                // }
            } else {
                if (item.WscwbbType === '利润类' || item.WscwbbType === '现金流量类' || item.WscwbbType === '现金流补充资料类') {
                    tempQC = 'QCWSLJFSE';
                    tempQM = 'WSLJFSE';
                    tempSQ = '';
                } else {
                    tempQC = 'QCWSS';
                    tempQM = 'WSS';
                    tempSQ = 'SNS';
                }
            }
            if (tempInex + 1 < 3 && (SQQMData.length || SQQMData1.length)) {
                filterStr = `${tempQC},${tempQM},${tempSQ}`;
            } else {
                filterStr = `${tempQC},${tempQM}`;
            }

            tempDataArr.push({
                tempQC,
                tempQM,
                tempSQ,
                filterStr
            });
        });

        console.log(tempDataArr, '@@@');


        yearDatas.data.forEach((item: any) => {
        });
        yearDatas.data1.forEach((item: any) => {


            // if (isTrue) {
            //     if (item.year_fieldName === 'QM') {
            //         return yearJoin.push(`${item.year_id}${tempQM}`);
            //     }
            //     if (item.year_fieldName === 'QC') {
            //         return yearJoin.push(`${item.year_id}${tempQC}`);
            //     }
            //     if (item.year_fieldName === 'SQQM') {
            //         return yearJoin.push(`${item.year_id}${tempSQ}`);
            //     }
            // } else {
            //     if (item.year_fieldName === 'BQ') {
            //         return yearJoin.push(`${item.year_id}${tempQM}`);
            //     }
            //     if (item.year_fieldName === 'SQ') {
            //         return yearJoin.push(`${item.year_id}${tempQC}`);
            //     }
            // }
        });

        // if (isTrue && SQQMData.length) {
        //     filterStr = `${tempQC},${tempQM},${tempSQ}`;
        // } else {
        //     filterStr = `${tempQC},${tempQM}`;
        // }
        // return { yearJoin, filterStr };
    }


    return (<div className="commonCpasTableBox">
        {/* {spinLoad && <SpinLoading loadString="" />} */}
        {/* <PageLoading
            isOpen={spinLoad}
            isMaskClose={false}
            content={loadingContent}
            width={200}
        /> */}
        {/* <FormsTitle formsTitleYear={showYaerData} ></FormsTitle> */}
        <div className="btnsTools">
            <Button
                type='default'
                className="defaultBtn"
                onClick={async () => {
                    let aaa: any = [];
                    const resData1 = await fetchTablePeriodList1111();
                    const newCmaps1 = updateCmaps111111(resData1, postCpasTableData)
                    console.log(resData1, '@@@');
                    // postCpasTableData.forEach((element: any, index: number) => {
                    //     if (index + 1 < 3) {
                    //         const newCmaps1 = updateCmaps111111(resData1.data, element, index + 1);
                    //         aaa.push(newCmaps1);
                    //     } else {
                    //         const newCmaps0 = updateCmaps111111(resData0.data, element, index + 1);
                    //         aaa.push(newCmaps0);
                    //     }
                    // });

                    console.log(aaa, '@@@');
                }}
                text='测试按钮'
            />
            {/* <Button
                type='default'
                className="defaultBtn"
                onClick={async () => {
                    setSpinLoad(true);
                    setLoadingContent('正在保存数据...');
                    const resSave = await saveToServer();
                    if (resSave || !resSave) {
                        setTimeout(() => {
                            setSpinLoad(false);
                            setLoadingContent(' ');
                        }, 500);
                    }

                }}
                text='保存'
            />
            <Button
                className="defaultBtnWhite purpleBtnUI"
                onClick={() => {
                    setShowMenuToolBar(!showMenuToolBar);
                }} text='模板设计'
            />
            <DropDownButton
                style={{ height: "30px", margin: "0px 8px 0 4px" }}
                text='导出'
                dropDownOptions={{
                    width: 120
                }}
                onItemClick={async (e: any) => {
                    if (e.itemData === '单个导出') {
                        exportChange();
                    } else {
                        batchExport();
                    }
                }}
                items={['单个导出', '批量导出']}
            />

            <DropDownButton
                style={{ height: "30px", marginRight: "4px" }}
                text='模板'
                dropDownOptions={{
                    width: 120
                }}
                onItemClick={(e: any) => {
                    if (e.itemData === '切换模板') {
                        changeTemplatePopupRef.current.showTemplate();
                    } else {
                        saveTemplatePopupRef.current.showTemplate();
                    }
                }}
                items={['切换模板', '保存模板']}
            />
            <div className='boxRight'></div>
            <Button
                className="defaultReloadBtnWhite"
                // disabled={tabsIndex > 5}
                render={() => (<CpasIcon type='icon-refresh' fontSize={16} />)}
                onClick={() => {
                    const realHandSonGridRef = getRealCPASTableRef();
                    if (realHandSonGridRef) {
                        const dataGrid = realHandSonGridRef.getCpasTableGrid();
                        console.log('数据@@@', dataGrid, serverDataLen);
                        if (dataGrid.data.length !== serverDataLen) {
                            cpasTableChangePupopRef.current.show();
                        } else {
                            cpasTableReload();
                        }
                    }
                }}
            /> */}
        </div>
        {/* <div className={`commonCpasTable ${commonCpasTableDisplay}  ${commonCpasTableNot} `}>
            <CpasTableFs
                tabGroup="fs-tab"
                tabLevel={2}
                ieType="json,draft"
                numberZeroReplace={cpasTableZeroReplace}
                type={CPASTableType}
                name={tableName}
                mapRowsList={rowsMapList}
                mapColumnsList={columnsMapList}
                isShowMenuToolBar={showMenuToolBar}
                verifyMode={true}
                notes={{ tid: cpasTableTid.current }}
                // gridData={copyServerData}
                tableDate={titleYearStr}
                tableTitle={titleName}
                tableRiDesc={`单位：${tableRiCurrency}`}
                tableLfDesc={`编制单位：${zcbfName}`}
                isTest={true}
                ref={cpasTableFsRef}
                draftSheetName={titleName}
                afterOnArtCellClick={(a, arr, cb) => {
                    const realrealHandSonGridRefRef = getRealCPASTableRef();
                    if (realrealHandSonGridRefRef) {
                        let p: any = [];
                        const resultList = realrealHandSonGridRefRef.articulationVerifyService.artParseResultList;
                        console.log(resultList);
                        if (cb !== null && cb[0]) {
                            resultList.forEach((item: any) => {
                                let havePro = item.beVerifiedCoordsMap;
                                console.log(
                                    "是否存在该属性",
                                    havePro?.hasOwnProperty(cb[0].currentFormula),
                                    havePro,
                                    cb[0].currentFormula
                                );

                                if (havePro?.hasOwnProperty(cb[0].currentFormula)) {
                                    p.push(item);
                                }
                            });
                            console.log(p, '@@@ 是否存在该属性 被校验项');
                            setResultListData({
                                verifyResult: p,
                                isBackAll: true,
                            });
                            closeDetail();
                        } else {
                            return notify("非校验项/已校验通过!", "error", 2000);
                        }
                    }
                }}
            ></CpasTableFs>
        </div> */}
        <CpasTableChangePupop ref={cpasTableChangePupopRef} tableSaveAndReload={saveAndReload} />
        <SaveTemplatePopup ref={saveTemplatePopupRef}
            okCallback={async (data: any) => {
                console.log(data, "@@@ 保存模板");
                const res: any = await saveTemplateApi({
                    dbName: dbname,
                    templateName: data,
                    type: "fs",
                    tableNames: tableNameGroup
                });
                if (res.success) {
                    notify("保存成功", "success", 2000);
                } else {
                    notify("保存失败", "error", 2000);
                }
            }}
            cancelCallback={() => {
                console.log("@@@ ， 取消");
            }}
        />
        <Details
            isOpen={openDetails}
            handleOpen={closeDetail}
            params={cpasTableFsRef?.current?.handsonTableFs}
            result={resultListData.verifyResult}
            isBackAll={resultListData.isBackAll}
            onBackAll={() => {
                setResultListData((oldData: any) => {
                    const newData = { ...oldData, isBackAll: false };
                    return newData;
                });
            }}
        />
        <PopupComponents ref={PopupComponentsRef} />

        <ChangeTemplatePopup ref={changeTemplatePopupRef}
            okCallback={async (data: any) => {
                console.log(data, "@@@ 切换模板");
                setSpinLoad(true);
                setLoadingContent('正在切换模板...');
                const resTemp: any = await templateInitApi({
                    dbName: dbname,
                    templateName: data,
                    tableNames: tableNameGroup,
                    type: 'fs',
                });
                if (resTemp.success) {
                    cpasChangeSpinAntTabs(false);
                    notify(`切换模板成功`, "success", 2000);
                    cpasChangeSpinAntTabs(true);
                } else {
                    notify(`${resTemp.msg}`, "error", 2000);
                }
                setSpinLoad(false);
                setLoadingContent(' ');
            }}
            cancelCallback={() => {
                console.log("@@@ ， 取消");
            }}
            changeData={{
                cloudTempType: "报告模板",
            }} />
    </div >)
})
export default React.memo(CommonCpasTable);
